<template>
  <el-dialog custom-class="mater_dialog" v-model="materVisible" width="815px" @close="handleClose">
    <template #title>
      <div class="dialog_header">素材库选择</div>
    </template>
    <div class="tab_box">
      <el-tabs v-model="baseId" class="base_tabs" @tab-change="tabClick">
        <el-tab-pane v-for="item in tabs" :key="item.id" :label="item.name" :name="item.id">
          <div class="pane-box">
            <el-input v-model="keyword" placeholder="搜索标题" type="text" :prefix-icon="Search" clearable @clear="clear" v-debounce="[getList]"> </el-input>
            <div class="pane-body-box">
              <keep-alive>
                <component v-if="item.id == baseId" :is="item.comName" @getData="getDataFun" :remainNum="remainNum" :baseList="baseList" :selectBaseList="selectBaseList" />
              </keep-alive>
            </div>
            <ZWPagination ref="PaginationRef" @submit="getList" />
          </div>
        </el-tab-pane>
      </el-tabs>
      <el-scrollbar class="group_box">
        <Grouping @submit="getChildGroup" :treeData="treeData"></Grouping>
      </el-scrollbar>
    </div>
    <template #footer>
      <div class="footer_box">
        <div class="right_footer">
          <!-- 本地上传 -->
          <template v-if="!SOP">
            <!-- <template v-if="!localUploadisShow.includes(baseId)">
              <el-button plain v-if="baseId == 6" @click="showCreatLocalLink">创建链接</el-button>
              <ZWUpload :upInfo="upInfo()" ref="ZWUploadRef" v-else @submit="getUploadFile" />
            </template> -->
          </template>
          <el-button v-else plain @click="cancel">取消</el-button>
          <el-button class="ml20" type="primary" @click="submitHandel">保存</el-button>
        </div>
        <div class="left_footer" v-show="baseId != 1">
          已选择<span>{{ selectNum }}</span
          >{{ `${baseId == 2 ? '张' : '个'}` }}{{ selectNameStr }},您还可选<span>{{ remainNum }}</span
          >个素材
        </div>
      </div>
    </template>
  </el-dialog>
  <CreateLocalLink ref="CreateLocalLinkRef" @getLocalLink="getUploadFile" />
  <!-- 视频播放器 -->
  <VideoWicket ref="VideoWicketRef" />
</template>
<script lang="ts" setup>
  import { ref, reactive, watch, shallowRef, computed } from 'vue'
  import { Search } from '@element-plus/icons-vue'
  import { GetVideoList } from '@/api/media'
  import { getGroupList, getVoiceList, getImageList, linkList, getFileList, getTextList, getGroupMarket } from '@/api/concreation'
  import { activityList } from '@/api/smartMarketing/luckyDraw'
  import Grouping from '@/components/channel/Grouping.vue'
  import ZWPagination from '@/components/ZWPagination.vue'

  import ImageList from '@/components/channel/ImageList.vue'
  import VideoList from '@/components/channel/VideoList.vue'
  import LinkList from '@/components/channel/LinkList.vue'
  import FileList from '@/components/channel/fileList.vue'
  import TextList from './TextList.vue'
  import AudioList from '@/components/channel/audioList.vue'
  import LuckDraw from '@/components/channel/luckDraw.vue'
  import CreateLocalLink from '@/components/channel/CreateLocalLink.vue'
  import VideoWicket from '@/components/channel/components/videoWicket.vue'
  import ZWUpload from '@/components/channel/ZWUpload.vue'

  import { ElMessage } from 'element-plus'
  import { deepClone } from '@/utils/utils'
  const emit = defineEmits(['submit'])

  import { useStore } from '@/store'
  const store = useStore()
  const CreateLocalLinkRef = ref(null)
  const showLuck = ref(false)
  const keyword = ref('')
  const materVisible = ref(false)
  const groupId = ref(0)
  const baseId = ref('2') // 图片
  const baseList = ref([]) // 列表
  const existFile = ref(9)
  const selectName = ref('2') // 图片
  const selectBaseList = ref([])
  const selectNameStr = ref('文本')
  const SOP = ref(false)
  const localUploadisShow= ref(['1', '8']) // 是否显示本地上传按钮
  //分组信息
  const treeData = ref([])
  const upInfo = () => {
    switch (baseId.value) {
      case '2': //图片
        return {
          type: 2,
          upFile: [],
          limitSize: 2,
          limitNum: remainNum.value,
          multiple: true,
          // acceptFile: '.jpg,.jpeg,.png,.gif,.bmp,.webp'
          acceptFile: '.jpg,.JPG,.jpeg,.JPEG,.png,.PNG'
        }
      case '4': // 视频
        return {
          type: 4,
          upFile: [],
          limitSize: 10,
          limitNum: 1,
          multiple: false,
          acceptFile: '.mp4'
        }
      case '5': // 文件
        return {
          type: 5,
          upFile: [],
          limitSize: 20,
          limitNum: 1,
          multiple: false,
          acceptFile: '.DOC,.DOCX,.XLS,.XLSX,.CSV,.PPT,.PPTX,.TXT,.PDF,.Xmind'
        }
      default:
        return {
          type: 2,
          upFile: [],
          limitSize: 2,
          limitNum: 1,
          multiple: true,
          acceptFile: '.jpg,.jpeg,.png,.gif,.bmp,.webp'
        }
    }
  }
  // tabs
  const tabs = ref([
    { id: '2', key: '1', name: '图片', nameStr: 'pic', total: 9, num: 0, comName: shallowRef(ImageList) },
    { id: '4', key: '2', name: '视频', nameStr: 'video', total: 9, num: 0, comName: shallowRef(VideoList) },
    { id: '5', key: '5', name: '文件', nameStr: 'file', total: 9, num: 0, comName: shallowRef(FileList) },
    { id: '6', key: '3', name: '链接', nameStr: 'link', total: 9, num: 0, comName: shallowRef(LinkList) },
    { id: '1', key: '-1', name: '文本', nameStr: 'text', total: 1, num: 0, comName: shallowRef(TextList) }
  ])
  const tabs2 = [
    { id: '2', key: '1', name: '图片', nameStr: 'pic', total: 9, num: 0, comName: shallowRef(ImageList) },
    { id: '4', key: '2', name: '视频', nameStr: 'video', total: 9, num: 0, comName: shallowRef(VideoList) },
    { id: '5', key: '5', name: '文件', nameStr: 'file', total: 9, num: 0, comName: shallowRef(FileList) },
    { id: '6', key: '3', name: '链接', nameStr: 'link', total: 9, num: 0, comName: shallowRef(LinkList) },
    { id: '1', key: '-1', name: '文本', nameStr: 'text', total: 1, num: 0, comName: shallowRef(TextList) },
    { id: '8', key: '6', name: '抽奖', nameStr: 'luck', total: 9, num: 0, comName: shallowRef(LuckDraw) }
  ]
  // 不显示选项的 id
  const handleShowTabs = (arrId: any) => {
    tabs.value = tabs.value.filter((item) => !arrId.includes(item.id))
  }
  const getTabItem = (num?: string | number) => {
    const key = num || baseId.value
    selectNameStr.value = tabs.value.find((item: any) => item.id == key)?.name
  }
  // baseId 转化字符串
  const changeBaseType = computed(() => {
    return tabs.value.filter((item: any) => item.id == baseId.value)[0].nameStr || 'pic'
  })
  const tabClick = (val?: any) => {
    selctInfo.value = {
      type: 0,
      typeStr: '',
      data: []
    }
    getTabItem(val)
    getGroupListData()
  }
  const handleClose = () => {
    keyword.value = ''
    materVisible.value = false
  }
  // 保存
  const submitHandel = () => {
    store.dispatch('table', {
      tableData: [],
      tableAll: false
    })
    if (selctInfo.value.data.length == 0) {
      ElMessage.error('请选择素材')
      return
    }
    handleClose()
    console.log('---1', selctInfo.value);
    emit('submit', selctInfo.value)
  }

  //取消
  const cancel = () => {
    handleClose()
  }

  const selctInfo = ref({
    type: 1,
    typeStr: 'text',
    data: []
  })
  // 选择数量
  const selectNum = computed(() => {
    return Number(selctInfo.value.data.length)
  })
  // 剩余数量
  const remainNum = computed(() => {
    return Number(existFile.value - selectNum.value)
  })
  // 素材库选的数据
  const getDataFun = (data: any) => {
    selctInfo.value = data
  }
  // 本地数据
  const getUploadFile = (data: any) => {
    if (data.type == 6) {
      data.local = true
      emit('submit', data)
    } else {
      let params = {
        local: true,
        type: baseId.value,
        data
      }
      emit('submit', params)
    }
    handleClose()
  }

  // 分组信息
  const getGroupListData = async () => {
    let res: any[] = [],
      defaultId = 0
    // 抽奖 分组
    if (baseId.value == 8) {
      res = await getGroupMarket({
        type: 13
      })
    } else {
      res = await getGroupList({
        type: baseId.value
      })
    }
    let result: any[] = [
      {
        name: '全部分组',
        id: 'all',
        nums: 0,
        children: []
      }
    ]
    if (res.data.length > 0) {
      result[0].nums = res.total
      result[0].children = res.data
      defaultId = res.data[0].id
    }
    treeData.value = result
    groupId.value = defaultId
    selectBaseList.value = []
    getList()
  }
  //  拿到分组的Id
  const getChildGroup = (val: number) => {
    groupId.value = val
    getList()
  }
  const getList = async (data?: any) => {
    let params = {
      title: keyword.value,
      group_id: groupId.value,
      page: data?.page || 1,
      page_size: data?.page_size || 15
    }
    let result = [],
      res = null,
      type = Number(baseId.value || data?.type)
    switch (type) {
      case 1: //文本
        res = await getTextList(params)
        break
      case 2: //图片
        res = await getImageList(params)
        break
      case 3: //语音
        res = await getVoiceList(params)
        break
      case 4: // 视频
        res = await GetVideoList(params)
        break
      case 5: // 文件
        res = await getFileList(params)
        break
      case 6:
      case 7: // 链接
        res = await linkList(params)
        break
      case 8: // 抽奖
        res = await activityList(params)
    }
    // if (type == 8) {
    //   result = res.list
    // } else {
    //   result = res.data
    // }
    result = res.data

    store.dispatch('pageTotal', res.total)
    baseList.value = result
    selectName.value = baseId.value
  }
  //本地上传
  const showCreatLocalLink = () => {
    CreateLocalLinkRef.value.showDialog()
  }
  //点击搜索框x号
  const clear = () => {
    getList()
  }
  defineExpose({
    materVisible,
    baseId,
    existFile,
    showLuck,
    SOP,
    handleShowTabs,
    localUploadisShow
  })

  watch(materVisible, (val) => {
    if (val) {
      if (showLuck.value) {
        tabs.value = tabs2
      }
      tabClick() // 分组信息
    }
  })
</script>

<style lang="scss">
  .mater_dialog {
    .el-dialog__header {
      padding: 0px;
    }
    .dialog_header {
      height: 50px;
      display: flex;
      padding-left: 20px;
      align-items: center;
      font-size: 16px;
      font-family: PingFangSC-Medium, PingFang SC;
      font-weight: 500;
      color: #33302d;
      line-height: 16px;
      border-bottom: 1px solid #eaeaea;
    }
    .el-dialog__body {
      padding: 0;
    }
    .el-dialog__footer {
      border-top: 1px solid #eaeaea;
      // padding-top: 0;
    }
  }
</style>
<style lang="scss" scoped>
  .tab_box {
    min-height: 600px;
    position: relative;
    .base_tabs {
      background: #f9f9f9;
      :deep(.el-tabs__content) {
        background: #fff;
      }
      :deep(.el-tabs__nav) {
        padding-left: 20px;
      }
    }
    .group_box {
      position: absolute;
      width: 170px;
      left: 0;
      top: 40px;
      height: calc(100% - 40px);
      background: #fff;
      border-right: solid 1px #eaeaea;
    }
    .pane-box {
      margin-top: 15px;
      padding-left: 190px;
      padding-right: 30px;
    }
    .pane-body-box {
      margin-top: 12px;
      width: 100%;
      height: 504px;
      overflow-y: scroll;
      white-space: nowrap;
    }
    .pane-body-box::-webkit-scrollbar {
      width: 0 !important;
    }
    .pane-body-box::-webkit-scrollbar {
      width: 0 !important;
      height: 0;
    }
  }
  .r_tab {
    position: absolute;
    top: 0px;
    right: 30px;
    line-height: 40px;
    .refresh {
      margin-right: 10px;
    }
    .active {
      color: #ff6b00;
      cursor: pointer;
      a {
        color: #ff6b00;
        text-decoration: none;
      }
    }
  }
  .footer_box {
    display: flex;
    justify-content: space-between;
    align-items: center;
    flex-direction: row-reverse;
    .left_footer {
      font-size: 14px;
      font-family: STHeitiSC-Light, STHeitiSC;
      font-weight: 300;
      color: #33302d;
      span {
        color: #ff6b00;
        margin: 0 5px;
      }
    }
    .right_footer {
      display: flex;
      justify-content: flex-end;
    }
  }
  .ml20 {
    margin-left: 20px;
  }
</style>
